<template>
	<view class="csfa">

		<view class="cs_01">
		</view>
		<!-- 中间 -->
		<view class="cs_02">
			<view v-if="listlength > 0">
				<scroll-view class="cs_02_01" style="height: 100%" scroll-y="true" scroll-with-animation="true">
					<view class="kuangheshop">
						<view v-for="(item, index) in list" :key="item.id" class="shops"
							@touchstart="startHandle($event, index)" @touchmove="moveHandle($event, index)"
							@touchend="endHandle($event, index)">

							<view class="shops-inner" :style="{ transform: `translateX(-${item.right}px)` }">
								<view>
									<checkbox-group @change="handleCheckboxChange(index, item)">
										<checkbox style="margin-top: 63rpx; transform: scale(0.8);" :value="item.id"
											:checked="item.checked" />
									</checkbox-group>
								</view>
								<view class="shops_01">

									<image :src="item.image" style="width: 200rpx; height: 200rpx;"></image>
									<text style="font-size: 34rpx; font-weight: bold;">{{ item.shopname }}</text>
									<text>商品单价: {{ item.price }}</text>

								</view>
								<view class="shops_02">
									<uni-number-box :min="1" :value="item.count" class="unbox"
										@change="handleNumberBoxChange($event, index)"></uni-number-box>
								</view>
							</view>

							<view class="delete-btn" @click="showConfirmDelete(item.sid)">
								<text>删除</text>
							</view>

						</view>
					</view>
				</scroll-view>
			</view>
			<view v-else class="weiyou">
				<image style="width: 250rpx; height: 250rpx;" src="../../../static/gwcnull.png"></image>
				<view style="margin-top: 40rpx;">您的购物车内暂无商品,快去选购吧!</view>
			</view>
		</view>
		<view class="cs_03">
			<view class="footzuo">
				<button class="quan"  @click="quanxuan">全选</button>
				<text>合计:{{ tt }}</text>
			</view>
			<view class="footyou">
				<button class="qu"  @click="gotojiesuan">去结算</button>
			</view>
		</view>
	</view>
	<tabBar></tabBar>
</template>





<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import tabBar from '../../../components/tabBar/tabBar.vue';
	import {
		http
	} from '/until/request.js';
import {
		useTokenStore
	} from '../../../store/token'; //导入pinia对象
const usetoken = useTokenStore()
	// 购物车数据模型长度
	const listlength = ref(0);

	// 合计金额
	const tt = ref(0);
	// 传递给后端的数据
	const chuanshu = ref({});
	// 请求的商品列表
	const requestshop = ref([]);
	// 商品索引
	const shopindex = ref([]);

	// 商品列表
	const list = ref([]);

	// 组件挂载后获取购物车数据
	onMounted(() => {
		gocar();
	});

	// 获取购物车数据
	const gocar = async () => {
		try {
			const response = await http({
				url: `/gocar/selectbyuid/` + usetoken.token.uid,
				method: 'get'
			});
			list.value = response.data;

			tt.value = calculateTotal();

			listlength.value = response.data.length;

			console.log("购物车数组长度");
			console.log(listlength.value);

		} catch (error) {
			console.error("获取购物车数据失败", error);
		}
	};

	// 计算合计金额
	const calculateTotal = () => {
		const total = list.value.reduce((total, item) => {
			if (item.checked) {
				return total + item.price * item.count;
			}
			return total;
		}, 0);
		return total;
	};

	// 处理复选框变化
	const handleCheckboxChange = (index, ss) => {
		const item = list.value[index];
		item.checked = !item.checked;
		tt.value = calculateTotal();

		const existingIndex = requestshop.value.findIndex(requestItem => requestItem.shopname === ss.shopname);
		if (existingIndex !== -1) {
			requestshop.value.splice(existingIndex, 1);
		} else {
			requestshop.value.push(ss);
		}
	};

	// 处理数量变化
	const handleNumberBoxChange = (value, index) => {
		const item = list.value[index];
		item.count = value;
		tt.value = calculateTotal();

		const existingIndex = requestshop.value.findIndex(requestItem => requestItem.shopname === item.shopname);
		if (existingIndex !== -1) {
			requestshop.value[existingIndex].count = item.count;
		}
	};

	// 全选功能
	const quanxuan = () => {
		const allChecked = list.value.every(item => item.checked);
		if (!allChecked) {
			list.value = list.value.map(item => ({
				...item,
				checked: true
			}));
			requestshop.value = [...list.value];
		} else {
			list.value = list.value.map(item => ({
				...item,
				checked: false
			}));
			requestshop.value = [];
		}
		tt.value = calculateTotal();
	};

// 去结算功能
const gotojiesuan = async () => {
    // 检查 shoplist 是否为空
    if (requestshop.value.length === 0) {
        uni.showToast({
            title: '购物车为空，请添加商品!',
            icon: 'none'
        });
        return; // 如果为空，直接返回，不执行后续操作
    }

    chuanshu.value = {};
    chuanshu.value.shoplist = requestshop.value;
    chuanshu.value.zongjie = tt.value;
    chuanshu.value.uid = usetoken.token.uid;

    const zx = await http({
        url: "/gocar/addzhangdan",
        method: "post",
        data: chuanshu.value
    });

    uni.showToast({
        title: zx.data,
        icon: 'success'
    });
    gocar();
};

	// 右滑删除功能
	const startX = ref("");

	// 删除按钮宽度
	const delBtnWidth = ref(50);

	// 开始触摸事件
	const startHandle = (e, index) => {
		const touch = e.touches[0];
		for (let i = 0; i < list.value.length; i++) {
			list.value[i].right = 0;
		}
		startX.value = touch.clientX;
	};

	// 移动触摸事件
	const moveHandle = (e, index) => {
		const touch = e.touches[0];
		var disX = startX.value - touch.clientX;
		if (disX >= 20) {
			if (disX > delBtnWidth.value) {
				disX = delBtnWidth.value;
			}
			list.value[index].right = disX;
		} else {
			list.value[index].right = 0;
		}
	};

	// 结束触摸事件
	const endHandle = (e, index) => {
		const good = list.value[index];
		if (good.right >= delBtnWidth.value / 2) {
			list.value[index].right = delBtnWidth.value;
		} else {
			list.value[index].right = 0;
		}
	};

	// 删除数据模型
	const isdelete = ref({
		uid: useTokenStore().token.uid,
		sid: ''
	});

	// 显示确认删除对话框
	const showConfirmDelete = (id) => {
		uni.showModal({
			title: '提示',
			content: '是否将此商品从购物车中移除？',
			success: function(res) {
				if (res.confirm) {
					delHandle(id);
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	};
	
	// 删除商品点击事件
	const delHandle = async (id) => {
		console.log("删除");
		console.log(id);
		isdelete.value.sid = id;

		const zx = await http({
			url: "/gocar/delectbyid",
			method: "post",
			data: isdelete.value
		});

		uni.showToast({
			title: zx.data,
			icon: 'success'
		});
		gocar();
	};
</script>




<style lang="less">
	page {
		width: 100%;
		height: 100%;
	}
	.quan{
			width: 500rpx;
			height: 70rpx;
			border-radius: 10rpx;
			background: linear-gradient(to right, #0496d9, #0496d9);
			color: white;
			font-size: 40rpx;
			box-shadow: 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.2);
			box-shadow: inset 0 -2rpx 0 rgba(0, 0, 0, 0.1), 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.2);
			text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.2);
			transition: background 0.3s ease, transform 0.3s ease;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		
			&:hover {
				transform: scale(1.05);
				background: linear-gradient(to right, #0496d9, #0496d9);
			}
		
			&:active {
				transform: scale(0.95);
				background: #005bb5;
			}
	}
.qu{
		width: 500rpx;
		height: 70rpx;
		border-radius: 10rpx;
		background: linear-gradient(to right, #0496d9, #0496d9);
		color: white;
		font-size: 35rpx;
		box-shadow: 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.2);
		box-shadow: inset 0 -2rpx 0 rgba(0, 0, 0, 0.1), 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.2);
		text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.2);
		transition: background 0.3s ease, transform 0.3s ease;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	
		&:hover {
			transform: scale(1.05);
			background: linear-gradient(to right, #0496d9, #0496d9);
		}
	
		&:active {
			transform: scale(0.95);
			background: #005bb5;
		}
}
	.weiyou {
		// border: 1px solid darkblue;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 35rpx;
	}

	.csfa {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;

		.cs_01 {
			width: 100%;
			height: 10vh;
			background: white;
			display: flex;
			align-items: center;
			justify-content: start;
			background-color: #0090fc;

			.cs_01_01 {
				background-color: #24b799;
				width: 90rpx;
				height: 50rpx;
				text-align: center;
				color: white;
				font-size: 30rpx;
				margin-left: 20rpx;
			}

			.cs_01_02 {
				font-size: 32rpx;
				margin-left: 20rpx;
			}
		}

		.cs_02 {
			overflow-y: auto;
			height: 68vh;
			width: 100%;
			display: flex;
			justify-content: space-evenly;

			.xuanze {
				width: 5%;
				margin-top: -20rpx;
			}

			.cs_02_01 {
				width: 100%;
				height: 100vh;

				.kuangheshop {
					display: flex;
					flex-direction: column;
					margin-left: 50rpx;
					// border: 1px solid blue;

					.shops {
						position: relative;
						width: 95%;
						height: 180rpx;
						// border: 1px solid gainsboro;
						// border: 1px solid black;
						// border-radius: 40rpx;
						margin-top: 30rpx;
						// margin-left: 0rpx;
						padding-left: 0rpx;
						display: flex;
						justify-content: space-between;

						.delete-btn {
							// border: 1px solid red;
							position: absolute;
							right: 0;
							top: 0;
							bottom: 0;
							width: 100rpx;
							// font-size: 40rpx;
							background-color: white;
							color: red;
							display: flex;
							align-items: center;
							justify-content: center;
							z-index: 1;
							box-shadow: 8px 5px 5px rgba(117, 160, 208, 0.3);
							// border-radius: 100rpx;
						}

						.shops-inner {
							// position: relative;
							width: 100vw;
							height: 100%;
							display: flex;
							justify-content: center;
							transition: transform 0.5s ease;
							box-shadow: 8px 5px 5px rgba(117, 160, 208, 0.3);
							background-color: white;
							// border-left: 100rpx;
							border-top-left-radius: 50px;
							/* 左上角圆角 */
							border-bottom-left-radius: 50px;
							/* 左下角圆角 */
							margin-right: 0rpx;
							z-index: 5;

						}

						.shops_01 {
							display: flex;
							flex-direction: column;
							justify-content: center;
							// border: 1px solid green;
							margin-right: 100rpx;
							margin-bottom: 40rpx;

						}

						.shops_02 {
							width: 40%;
							display: flex;
							flex-direction: column;
							justify-content: flex-end;
							padding-right: 10rpx;
							align-items: flex-end;
							// border: 1px solid firebrick;

							.unbox {
								margin-bottom: 15rpx;
								margin-left: -90rpx;
							}
						}
					}
				}
			}
		}

		.cs_03 {
			line-height: 100rpx;
			background-color: white;
			display: flex;
			justify-content: space-between;
			margin-top: 30rpx;

			.footzuo {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 20rpx;

				button {
					font-size: 20rpx;
					width: 130rpx;
					height: 60rpx;
					margin-right: 20rpx;
				}
			}

			.footyou {
				display: flex;
				align-items: center;
				button {
					margin-right: 20rpx;
					font-size: 30rpx;
					width: 230rpx;
					height: 60rpx;
					color: white;
					background-color: #0090fc;
					border-radius: 150rpx;
				}
			}
		}
	}
</style>